<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>主页</title>
</head>

<body>
  <ul id="list"></ul>

  <div id="total">0</div>


  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    // 获取数据列表
    console.log(axios); // axios 是 fetch 替代品
    axios({
      method: 'get',
      url: '/api/getGoodsList',
    }).then(res => {
      console.log(res);
      list.innerHTML = res.data.list.map(item => {
        return `
          <li data-id="${item.id}">
            <span>${item.name}</span>
            <span>${item.price}</span>
            <button data-less="${item.id}">-</button>
            <span data-num="${item.id}">${item.num}</span>
            <button data-add="${item.id}">+</button>
          </li>
        `
      }).join('')


      let sum = 0;
      res.data.list.forEach(item => {
        sum += item.num * item.price
      })
      total.innerHTML = sum;
    })

    list.onclick = function (e) {
      console.dir(e.target);
      if ('add' in e.target.dataset) {
        axios({
          method: 'get',
          url: `/api/goodsNumAdd?id=${e.target.dataset.add}`,
        })
      }
      else if ('less' in e.target.dataset) {
        if (e.target.parentNode.children[3].innerHTML == 1) {
          alert('现在购物车中的数量为 1, 不能再减少了')
          return;
        }
        axios({
          method: 'get',
          url: `/api/goodsNumLess?id=${e.target.dataset.less}`,
        })
      }


      location.reload();
    }
  </script>
</body>


</html>